#ifndef VECTORDATABASE_H
#define VECTORDATABASE_H

#include <QObject>
#include <QVector>
#include <QString>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QFile>
#include <QDir>

struct DocumentChunk {
    int id;
    QString text;
    QString filePath;
    QVector<float> embedding;

    DocumentChunk() : id(-1) {}
    DocumentChunk(const QString &t, const QString &fp, const QVector<float> &emb)
        : id(-1), text(t), filePath(fp), embedding(emb) {}

    QJsonObject toJson() const;
    void fromJson(const QJsonObject &json);
};

class VectorDatabase : public QObject
{
    Q_OBJECT

public:
    explicit VectorDatabase(QObject *parent = nullptr);
    bool initialize();
    bool insertDocument(const DocumentChunk &chunk);
    QVector<DocumentChunk> searchSimilar(const QVector<float> &queryVector, int topK);
    bool saveToFile();
    bool loadFromFile();
    bool documentExists(const QString &filePath, const QString &text) const;
    bool clearDatabase();

private:
    QString m_filePath=QDir::currentPath() +"/KyAiData/vector_database.json";
    QVector<DocumentChunk> m_documents;
    int m_nextId;
    float cosineSimilarity(const QVector<float> &vec1, const QVector<float> &vec2);
};

#endif // VECTORDATABASE_H
